from .token import *
from DialogDiagnosis.model.model import comm_model_api
from DialogDiagnosis.DataService.model import NulCommunicationList


# Results:
class CommunicationResult(Result):

    def __init__(self, result: str = ''):
        self.result: str = result

    def serialize(self) -> dict:
        dictionary: dict = {
            'result': self.result
        }
        return dictionary


# Util:
def save_communication_user(openid: str, unionid: str, comm: str) -> None:
    entry: NulCommunicationList = NulCommunicationList(Speaker=1, OpenID=openid, UnionID=unionid, Content=comm)
    entry.save()


def save_communication_system(result: str) -> None:
    entry: NulCommunicationList = NulCommunicationList(Speaker=0, Content=result)
    entry.save()


# Communication Controller:
def communication(request: HttpRequest) -> JsonResponse:
    try:
        token_info: TokenInfo = verify_request_token(request)
        body: dict = decode_std_body(request)

        comm: str = get_json_value_or_except(body, 'communication', str)
        result: str = comm_model_api(comm)

        save_communication_user(token_info.openid, token_info.unionid, comm)
        save_communication_system(result)

    except NulException as e:
        return response_except(e)

    return response(CommunicationResult(result))
